# coding:utf-8

from django.http import HttpResponseRedirect,JsonResponse,HttpResponse
from django.shortcuts import render
from django.contrib import auth
from django.contrib.auth.models import User,Group
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from rbac.models import *
from .database import *


def login(request):
    if request.session.get('username') is not None:
        return HttpResponseRedirect('index/')
    if request.method == "POST":
        PermissionList = set()
        username = request.POST.get('username','')
        password = request.POST.get('password','') 
        user = auth.authenticate(username=username, password=password)
        if user and user.is_active:
            '''
            对应关系：
            User -->  UserRole  --> RolePermission  --> Permissions
            1. 获取用户 id
            2. 通过用户 id 获取 用户的role id
            3. 通过role id 获取 permissions id
            4. 通过 permissions id 找出所有对应的url
            '''
            # 获取用户id
            user_info = User.objects.get(username=username)
            print("当前登陆用户的id: {}, 登陆用户名: {}".format(user_info.id, user_info.username))
            
            # 获取用户拥有的所有role
            try:
                user_role = UserRole.objects.get(user=user_info.id)
            except Exception as e:
                return render(request, 'login.html', {"message":"当前用户并未正确的分配角色"})
            for ur in user_role.role.all():
                #print("{} -->  {}".format(ur.id,ur.name))
                # 获取所属role 对应的权限
                prs=RolePermission.objects.filter(role_id=ur.id)
                for pr in prs:
                    #print(pr.id,pr.title,pr.role,pr.role_id)
                    for p in pr.permissions.all():
                        #print(p.id,p.title,p.url)
                        PermissionList.add(p.url)
            if not PermissionList:
                return render(request, 'login.html', {"message":"当前用户所属角色并未分配权限"})
            request.session['PermissionList'] = list(PermissionList)
            
            auth.login(request,user)
            request.session['username'] = username

            return HttpResponseRedirect('index/')
        else:
            return render(request, 'login.html', {"message":"用户名不存在，或者账号密码错误！"})
    else:
        return render(request, 'login.html')


@login_required()
def index(request):
    return render(request, 'index.html', {"loginuser":request.user,})


def logout(request):
    auth.logout(request)
    return HttpResponseRedirect('/login')

def forbidden(request):
    return render(request, '403.html', {"loginuser":request.user,})
